<template>
    <div class="relation-annotation-tool" v-if="visible">
        <div class="relation-dialog">
            <div class="dialog-header">
                <h3>添加关系标注</h3>
                <button @click="close" class="close-button">×</button>
            </div>
            <div class="dialog-body">
                <div class="entity-selection">
                    <div class="entity-item">
                        <div class="entity-label">源实体:</div>
                        <div class="entity-value" :style="sourceEntityStyle">
                            {{ sourceEntityText || '请先选择源实体' }}
                        </div>
                    </div>
                    <div class="relation-arrow">→</div>
                    <div class="entity-item">
                        <div class="entity-label">目标实体:</div>
                        <div class="entity-value" :style="targetEntityStyle">
                            {{ targetEntityText || '请先选择目标实体' }}
                        </div>
                    </div>
                </div>
                <div class="relation-selection">
                    <div class="relation-label">选择关系类型:</div>
                    <div class="relation-list">
                        <div v-for="relation in availableRelations" :key="relation.id" class="relation-item"
                            :class="{ 'selected': selectedRelation && selectedRelation.id === relation.id }"
                            @click="selectRelation(relation)">
                            {{ relation.text }}
                        </div>
                        <div v-if="availableRelations.length === 0" class="no-relations">
                            没有可用的关系类型，请先在关系类中定义关系
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialog-footer">
                <button @click="close" class="cancel-button">取消</button>
                <button @click="confirmRelation" class="confirm-button" :disabled="!canConfirm">
                    确定
                </button>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
// 定义props
const props = defineProps({
    visible: Boolean,
    editor: Object,
    sourceEntity: Object,
    targetEntity: Object
});
// 定义emit
const emit = defineEmits(['update:visible', 'relationAdded']);
// 响应式状态
const sourceEntityText = computed(() => props.sourceEntity?.text || '');
const targetEntityText = computed(() => props.targetEntity?.text || '');
const sourceEntityStyle = computed(() => props.sourceEntity?.style || {});
const targetEntityStyle = computed(() => props.sourceEntity?.style || {});
// 可用的关系列表
const availableRelations = ref([]);
// 选中的关系
const selectedRelation = ref(null);
// 是否可以确认
const canConfirm = computed(() => {
    return props.sourceEntity && props.targetEntity && selectedRelation.value;
});
// 监听对话框显示状态变化
watch(() => props.visible, (newValue) => {
    if (newValue) {
        // 对话框显示时，加载可用的关系
        loadAvailableRelations();
    } else {
        // 对话框关闭时，重置状态
        selectedRelation.value = null;

        // 清除编辑器中所有实体的临时高亮样式
        if (props.editor) {
            const entitySpans = props.editor.getBody().querySelectorAll('span.entity');
            entitySpans.forEach(span => {
                span.style.outline = '';
            });
        }
    }
});
// 加载可用的关系
function loadAvailableRelations() {
    // 从全局获取关系列表
    const relations = window.relations || [];
    console.log('加载可用关系，全局关系列表:', relations);
    console.log('源实体:', props.sourceEntity);
    console.log('目标实体:', props.targetEntity);
    // 如果有源实体和目标实体，筛选适用的关系
    if (props.sourceEntity && props.targetEntity) {
        availableRelations.value = relations.filter(relation => {
            // 记录日志以便调试
            console.log(`检查关系: ${relation.id}, 源=${relation.source}, 目标=${relation.target}`);
            console.log(`当前选择: 源=${props.sourceEntity.id}, 目标=${props.targetEntity.id}`);
            // 检查源实体ID和目标实体ID是否完全匹配
            const idMatch = relation.source === props.sourceEntity.id &&
                relation.target === props.targetEntity.id;
            // 如果ID不匹配，检查实体类型是否匹配
            // 从实体ID中提取类型信息（假设ID格式为"类型_编号"）
            let typeMatch = false;
            if (!idMatch) {
                const sourceType = props.sourceEntity.id.split('_')[0];
                const targetType = props.targetEntity.id.split('_')[0];
                const relationSourceType = relation.source.split('_')[0];
                const relationTargetType = relation.target.split('_')[0];
                console.log(`类型比较: 源类型=${sourceType}, 关系源类型=${relationSourceType}`);
                console.log(`类型比较: 目标类型=${targetType}, 关系目标类型=${relationTargetType}`);
                typeMatch = relationSourceType === sourceType &&
                    relationTargetType === targetType;
            }
            return idMatch || typeMatch;
        });
        console.log('找到的可用关系:', availableRelations.value);
    } else {
        availableRelations.value = [];
    }
}
// 选择关系
function selectRelation(relation) {
    selectedRelation.value = relation;
}
// 确认添加关系
function confirmRelation() {
    if (!canConfirm.value) {
        ElMessage.warning('请先选择源实体、目标实体和关系类型');
        return;
    }
    // 获取编辑器实例
    const editor = props.editor;
    if (!editor) {
        ElMessage.error('编辑器实例不存在');
        return;
    }
    try {
        // 创建关系标注
        createRelationAnnotation(editor, props.sourceEntity, props.targetEntity, selectedRelation.value);
        // 更新关系标记计数
        updateRelationCount(selectedRelation.value.id);
        // 发送关系添加事件
        emit('relationAdded', {
            sourceEntity: props.sourceEntity,
            targetEntity: props.targetEntity,
            relation: selectedRelation.value
        });
        // 关闭对话框
        close();
    } catch (error) {
        console.error('添加关系标注失败:', error);
        ElMessage.error('添加关系标注失败: ' + error.message);
    }
}
// 创建关系标注
function createRelationAnnotation(editor, sourceEntity, targetEntity, relation) {
    // 获取源实体和目标实体的DOM元素
    const content = editor.getContent();
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, 'text/html');
    // 查找所有带有data-entity-id属性的span元素
    const entitySpans = doc.querySelectorAll('span.entity[data-entity-id]');
    // 找到源实体和目标实体的DOM元素
    let sourceSpan = null;
    let targetSpan = null;
    entitySpans.forEach(span => {
        const entityId = span.getAttribute('data-entity-id');
        if (entityId === sourceEntity.id) {
            sourceSpan = span;
        } else if (entityId === targetEntity.id) {
            targetSpan = span;
        }
    });
    if (!sourceSpan || !targetSpan) {
        throw new Error('未找到源实体或目标实体的DOM元素');
    }
    // 为源实体和目标实体添加关系属性
    sourceSpan.setAttribute('data-relation-id', relation.id);
    sourceSpan.setAttribute('data-relation-role', 'source');
    // 为源实体添加目标实体的属性信息，包含目标实体ID和文本内容
    sourceSpan.setAttribute('data-relation-target', targetEntity.id);
    sourceSpan.setAttribute('data-relation-target-text', targetEntity.text);
    sourceSpan.setAttribute('data-relation-target-type', targetEntity.id.split('_')[0]);
    targetSpan.setAttribute('data-relation-id', relation.id);
    targetSpan.setAttribute('data-relation-role', 'target');
    targetSpan.setAttribute('data-relation-source', sourceEntity.id);
    // 更新编辑器内容
    editor.setContent(doc.body.innerHTML);
}
// 更新关系标记计数
function updateRelationCount(relationId) {
    // 如果存在全局更新方法，则调用它来更新关系标记数量
    if (typeof window.updateRelationMarkedCount === 'function') {
        // 创建一个对象来存储关系ID的计数
        const relationCounts = {};
        relationCounts[relationId] = (relationCounts[relationId] || 0) + 1;
        // 创建一个对象来存储关系ID的标注文本内容
        const relationTexts = {};
        relationTexts[relationId] = relationTexts[relationId] || [];
        relationTexts[relationId].push(`${sourceEntityText.value} → ${targetEntityText.value}`);
        // 创建一个对象来存储关系ID的检查状态
        const checkedStatus = {};
        checkedStatus[relationId] = checkedStatus[relationId] || [];
        checkedStatus[relationId].push(true);
        // 调用全局更新方法
        window.updateRelationMarkedCount(relationCounts, relationTexts, checkedStatus);
    }
}

// 关闭对话框
function close() {
    emit('update:visible', false);
}
</script>

<style scoped>
.relation-annotation-tool {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.relation-dialog {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    width: 500px;
    max-width: 90%;
    overflow: hidden;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
}

.dialog-header h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.close-button {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #999;
}

.dialog-body {
    padding: 20px;
}

.entity-selection {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
}

.entity-item {
    flex: 1;
}

.entity-label {
    font-weight: bold;
    margin-bottom: 5px;
}

.entity-value {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    min-height: 20px;
}

.relation-arrow {
    font-size: 24px;
    margin: 0 15px;
    color: #666;
}

.relation-selection {
    margin-top: 20px;
}

.relation-label {
    font-weight: bold;
    margin-bottom: 10px;
}

.relation-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    max-height: 150px;
    overflow-y: auto;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
}

.relation-item {
    padding: 6px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
}

.relation-item:hover {
    background-color: #f5f5f5;
}

.relation-item.selected {
    background-color: #409eff;
    color: white;
    border-color: #409eff;
}

.no-relations {
    color: #999;
    font-style: italic;
    padding: 10px;
    text-align: center;
    width: 100%;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
}

.dialog-footer button {
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-left: 10px;
}

.cancel-button {
    background-color: #f0f0f0;
    border: none;
    color: #333;
}

.confirm-button {
    background-color: #409eff;
    border: none;
    color: white;
}

.confirm-button:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
}
</style>
